import 'package:flutter/material.dart';
import '../widget/gradient_btn.dart';
import '../widget/radio_group.dart';
import '../widget/slider_widget.dart';
import '../static_var.dart';
import '../model/my_socket.dart';
import '../utils.dart';
import '../widget/scaffold_page.dart';
import './page_room.dart';
import '../model/ex_stream.dart';
import '../widget/loading_gradient_btn.dart';
import '../model/cus_dialog.dart';
import '../model/socket_msg.dart';
import '../user_proof.dart';
import '../widget/friends_list.dart';
import '../widget/loading_widget.dart';
import '../widget/nobk_dialog.dart';
import '../widget/msg_dialog.dart';
import '../widget/red_point.dart';

class PageLobby extends StatelessWidget {
  final bool isSortLogin;
  final double mainBtnWidth = 120;
  ExStream<Map> userInfoStream = ExStream<Map>(UserProof.userInfo);
  ExStream<bool> btnJoinLoadingStream;
  ExStream<bool> btnCreateLoadingStream;

  ExStream<bool> initLoadingStream = ExStream<bool>(false);

  ExStream<Map> msgDataStream = ExStream<Map>.broadcast({});
  BuildContext widgetContext;

  int inviteDialogCount = 0;
  
  PageLobby({this.isSortLogin = false}) {
    MySocket.addListener(listenerPge:SocketListenerPage.lobby, callback: (dynamic data){
      var tData = data['data'];
      ResMsgType msgType = SocketMsg.resMsgTypeFromStr[data['type']];
      if(ResMsgType.invite == msgType) {
        if(inviteDialogCount > 0) {
          Navigator.of(this.widgetContext).pop();
        }
        inviteDialogCount ++;
        showDialog(
          context: this.widgetContext,
          builder: (BuildContext context) {
            return SimpleDialog(
              contentPadding: EdgeInsets.all(12),
              titlePadding: EdgeInsets.only(top: 15, bottom: 0, left: 12, right: 12),
              title: Container(
                alignment: Alignment.center,
                child: Text('提示', style: TextStyle(color: StaticVar.yellowColor, fontSize: 25),),
              ),
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Text(tData['uname'].toString(), style: TextStyle(color: StaticVar.blueColor),),
                    Container(width: 5,),
                    Text('邀请您'),
                    Container(width: 5,),
                    Text(StaticVar.roomType[tData['type']], style: TextStyle(color: StaticVar.blueColor),)
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Text('房间号：'),
                        Text(tData['id'].toString(), style: TextStyle(color: StaticVar.blueColor))
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Text('底注：'),
                        Text(tData['antes'].toString(), style: TextStyle(color: StaticVar.blueColor))
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Text('人数：'),
                        Text(tData['need_player_count'].toString(), style: TextStyle(color: StaticVar.blueColor))
                      ],
                    )
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      GradientBtn(child: Text('拒绝', style: TextStyle(color: Colors.white),), pressed: (){
                        Navigator.of(this.widgetContext).pop();
                      }, colorType: 2,),
                      GradientBtn(child: Text('接受', style: TextStyle(color: Colors.white)), pressed: (){
                        Navigator.of(this.widgetContext).pop();
                        Navigator.of(this.widgetContext).pushReplacement(MaterialPageRoute(builder: (_){return ScaffoldPage(child: PageRoom(roomId: tData['id'], roomPwd: tData['pwd'], roomType: tData['type'], needPlayerCount: tData['need_player_count'], antes: int.parse(tData['antes'])));}));
                      },)
                    ],
                  ),
                )
              ],
            );
          }
        ).then((onValue){
          this.inviteDialogCount --;
        });
      }else if(ResMsgType.updateMsgCount == msgType) {
        msgDataStream.setData(tData);
      }else if(ResMsgType.userInfo == msgType) {
        msgDataStream.setData(tData['msg']);
      }
    });
  }

  void initUserInfoCallback(Map userInfo) {
    initLoadingStream.setData(true);
    MySocket.initSingleSocket();
    UserProof.setUserInfo(userInfo['user_info']);
    this.userInfoStream.setData(userInfo['user_info']);
    msgDataStream.setData(userInfo['msg']);
  }
  void initUserInfo() async {
    if(isSortLogin) {
      Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/shortLogin', data: {'user_id': UserProof.userId}, success: (res){
        initUserInfoCallback(res['data']);
      });
    }else {
      Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/getUserInfo', data: {'user_id': UserProof.userId}, success: (res){
        initUserInfoCallback(res['data']);
      });
    }
  }

  void showFriendsDialog() {
    showDialog(
      context: this.widgetContext,
      builder: (BuildContext context) {
        return FriendsList();
      }
    );
  }
  Widget userTitle() {
    return StreamBuilder<Map>(
      stream: userInfoStream.stream,
      initialData: userInfoStream.data,
      builder: (BuildContext context, AsyncSnapshot<Map> streamData) {
        Map userInfo = streamData.data;
        List<Widget> userInfoWidgets = [];
        if(null != userInfo) {
          if(null != userInfo['uname']) {
            userInfoWidgets.add(Icon(IconData(userInfo['sex']==0?0xe602:0xe640, fontFamily: 'iconfont'), size: 16, color: Colors.white));
            userInfoWidgets.add(Container(width: 6));
            userInfoWidgets.add(Text(userInfo['uname'].toString(), style: TextStyle(color: Colors.white, fontSize: 18)));
            userInfoWidgets.add(Container(width: 40));
          }
          if(null != userInfo['asset']) {
            userInfoWidgets.add(Icon(IconData(0xe647, fontFamily: 'iconfont'), size: 16, color: Colors.white));
            userInfoWidgets.add(Container(width: 6));
            userInfoWidgets.add(Text(userInfo['asset'].toString(), style: TextStyle(color: Colors.white)));
          }
          if(userInfoWidgets.length > 0) {
            userInfoWidgets.add(Container(width: 40));
          }
          userInfoWidgets.add(
            GestureDetector(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 5),
                child: Icon(IconData(0xe60c, fontFamily: 'iconfont'), size: 16, color: Colors.white),
              ),
              onTap: (){
                showFriendsDialog();
              },
            )
          );
        }
        return Container(
          color: Color.fromARGB(255, 90,122,225),
          padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  children: userInfoWidgets,
                ),
              ),
              GestureDetector(
                child: Text('注销', style: TextStyle(color: Colors.white),),
                onTap: (){
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        content: Text('确定注销'),
                        actions: <Widget>[
                          FlatButton(child: Text('确定'), onPressed: (){
                            MySocket.sendMsg(type: SendMsgType.loginout);
                            UserProof.cleanUserinfo();
                            Navigator.of(context).pop();
                            Navigator.of(context).pushReplacementNamed('/login');
                          }),
                          FlatButton(child: Text('取消', style: TextStyle(color: Colors.blueGrey),), onPressed: (){
                            Navigator.of(context).pop();
                          })
                        ]
                      );
                    }
                  );
                  
                },
              )
            ],
          )
        );
      },
    );
  }
  bool stringNotEmpty(String str) {
    return null != str && '' != str;
  }
  void createRoom({String roomType, int playerCount, String roomPwd, int roomAntes}) {
    bool btnStreamData = this.btnCreateLoadingStream.data;
    if(null == btnStreamData || !btnStreamData) {
      if(stringNotEmpty(roomPwd)) {
        this.btnCreateLoadingStream.setData(true);
        Utils.verifyPost(context: this.widgetContext, url: StaticVar.remoteUrl + '/createRoom', data: {'room_type': roomType, 'player_count': playerCount.toString(), 'room_pwd':roomPwd, 'antes': roomAntes.toString()},
          success: (res){
            Map data = res['data'];
            Navigator.of(this.widgetContext).pop();
            Navigator.of(this.widgetContext).pushReplacement(MaterialPageRoute(builder: (_){return ScaffoldPage(child: PageRoom(roomId: data['id'], roomPwd: roomPwd, roomType: data['type'], needPlayerCount: data['need_player_count'], antes: int.parse(data['antes'])));}));
          },finnaly: (){
            this.btnCreateLoadingStream.setData(false);
          }
        );
      }else {
        CusDialog.showError(this.widgetContext, '房间密码不能为空');
      }
    }
  }
  void showCreateRoom() {
    String gameType = 'doudizhu';
    double playerCount = 3.0;
    String roomPwd = '';
    int roomAntes = 0;
    this.btnCreateLoadingStream = ExStream<bool>(false);
    showDialog(
      context: this.widgetContext,
      builder: (BuildContext context) {
        return SimpleDialog(
          contentPadding: EdgeInsets.all(10),
          children:<Widget>[
            Column(
              children: <Widget>[
                RadioGroup(data: StaticVar.roomType, defaulVlue: gameType, onChange: (val){gameType = val;}),
                Container(height: 10),
                Row(
                  children: <Widget>[
                    Text('人数'),
                    Expanded(
                      child: SliderWidget(min: 2, max: 6, defaultVal: playerCount, onChange: (val){playerCount = val;}, divisions: 4),
                    )
                  ],
                ),
                Container(height: 10),
                TextField(keyboardType:TextInputType.numberWithOptions(), cursorRadius: Radius.circular(0), decoration: InputDecoration(labelText: '底注', contentPadding:EdgeInsets.all(0), prefixIcon: Icon(Icons.attach_money)), onChanged: (val){roomAntes = int.parse(val);}),
                Container(height: 10),
                TextField(decoration: InputDecoration(labelText: '密码', contentPadding:EdgeInsets.all(0), prefixIcon: Icon(Icons.vpn_key)), cursorRadius: Radius.circular(0), obscureText: true, onChanged: (val){roomPwd = val;},onSubmitted: (val){
                  createRoom(roomType: gameType, playerCount: playerCount.toInt(), roomPwd: roomPwd, roomAntes: roomAntes);
                },),
                Container(height: 10),
                
                LoadingGradientBtn(exStream: this.btnCreateLoadingStream, width: 100, height: 30, child: Text('创建', style: TextStyle(color: Colors.white)), pressed: (){
                  createRoom(roomType: gameType, playerCount: playerCount.toInt(), roomPwd: roomPwd, roomAntes: roomAntes);
                })
              ],
            )
          ]
        );
      },
    );
  }
  void joinRoom({String roomId, String roomPwd}) {
    bool btnStreamData = this.btnJoinLoadingStream.data;
    if(null == btnStreamData || !btnStreamData) {
      if(stringNotEmpty(roomId) && stringNotEmpty(roomPwd)) {
        this.btnJoinLoadingStream.setData(true);
        Utils.verifyPost(context: this.widgetContext, url: StaticVar.remoteUrl + '/enterRoom', data: {'room_id': roomId, 'room_pwd': roomPwd}, success: (res){
          Map data = res['data'];
          Navigator.of(this.widgetContext).pop();
          Navigator.of(this.widgetContext).pushReplacement(MaterialPageRoute(builder: (_){return ScaffoldPage(child: PageRoom(roomId: data['id'], roomPwd: roomPwd, roomType: data['type'], needPlayerCount: data['need_player_count'], antes: int.parse(data['antes'])));}));
        },finnaly: (){
          this.btnJoinLoadingStream.setData(false);
        });
      }else {
        CusDialog.showError(this.widgetContext, '房间号和房间密码不能为空');
      }
    }
  }
  void showJoinRoom() {
    String roomId = '';
    String roomPwd = '';
    this.btnJoinLoadingStream = ExStream<bool>(false);
    showDialog(
      context: this.widgetContext,
      builder: (BuildContext context) {
        return SimpleDialog(
          contentPadding: EdgeInsets.all(10),
          children:<Widget>[
            Column(
              children: <Widget>[
                TextField(decoration: InputDecoration(labelText: '房间号', contentPadding:EdgeInsets.all(0), prefixIcon: Icon(Icons.home)), cursorRadius: Radius.circular(0), onChanged: (val){roomId = val;}),
                Container(height: 20),
                TextField(decoration: InputDecoration(labelText: '密码', contentPadding:EdgeInsets.all(0), prefixIcon: Icon(Icons.vpn_key),), cursorRadius: Radius.circular(0), obscureText: true, onChanged: (val){roomPwd = val;},onSubmitted:(val){
                  joinRoom(roomId: roomId, roomPwd: roomPwd);
                }),
                Container(height: 10),

                LoadingGradientBtn(exStream: this.btnJoinLoadingStream, width: 100, height: 30, child: Text('加入', style: TextStyle(color: Colors.white)), pressed: (){
                  joinRoom(roomId: roomId, roomPwd: roomPwd);
                })
              ],
            )
          ]
        );
      },
    );
  }

  void showMessageDialog(BuildContext context) {
    nobkDialog(
      context: context,
      builder: (BuildContext context) {
        return MsgDialog(msgStream: msgDataStream);
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    this.widgetContext = context;
    initUserInfo();
    
    return StreamBuilder<bool>(
      stream: initLoadingStream.stream,
      initialData: initLoadingStream.data,
      builder: (BuildContext context, AsyncSnapshot<bool> initLoadingData){
        return initLoadingData.data ? Column(
          children: <Widget>[
            this.userTitle(),
            Expanded(
              child: Stack(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      
                      GradientBtn(width: this.mainBtnWidth, height: 38, child: Text('加入房间', style: TextStyle(color: Colors.white)), pressed: (){
                        this.showJoinRoom();
                      }),
                      Container(width: 90),
                      GradientBtn(width: this.mainBtnWidth, height: 38, child: Text('创建房间', style: TextStyle(color: Colors.white)), pressed: (){
                        this.showCreateRoom();
                      })
                    ]
                  ),
                  Positioned(
                    bottom: 30,
                    right: 30,
                    child: GestureDetector(
                      child: StreamBuilder<Map>(
                        stream: msgDataStream.stream,
                        initialData: msgDataStream.data,
                        builder: (BuildContext context, AsyncSnapshot<Map> data) {
                          int msgCount = data.data['count'] == null ? 0 : data.data['count'];
                          
                          return Stack(
                            overflow: Overflow.visible,
                            children: <Widget>[
                              Icon(IconData(0xe6a5, fontFamily: 'iconfont'), size: 23, color: Colors.white),
                              RedPoint(count: msgCount,)
                            ],
                          );
                        },
                      ),
                      onTap: (){
                        showMessageDialog(context);
                      },
                    ),
                  )
                ],
              )
            )
          ],
        ) : LoadingWidget();
      },
    );
  }
}